package com.powernobug.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-13
 * @Description:
 */
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
    }

    private JsonUtil() {}

    public static String writeJson(Object obj) {
        String json = null;

        try {json = objectMapper.writeValueAsString(obj);}
        catch (JsonProcessingException e) {
            System.out.println("转换Json时错误！");
            e.printStackTrace();
        }
        return json;
    }

    public static <T> T readJson(String json, Class<T> type) {
        T t = null;
        try {t = objectMapper.readValue(json, type);}
        catch (JsonProcessingException e) {
            System.out.println("Json解析时错误！");
            e.printStackTrace();
        }
        return t;
    }

    public static<T,V> Map<T, V> readRequestLineToMap(HttpServletRequest req) throws IOException {
        String jsonQuery = req.getReader().readLine();
        return JsonUtil.readJson(jsonQuery, Map.class);
    }
}
